package org.smartboot.sosa.rpc.netty;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.smartboot.sosa.rpc.RpcConstant;
import org.smartboot.sosa.rpc.Session;
import org.smartboot.sosa.rpc.process.MessageReceiver;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

/**
 * 接受业务消息
 * 
 * @author Seer
 * @version RpcClientHandler.java, v 0.1 2015年11月22日 下午3:01:00 Seer Exp.
 */
public class RpcChannelHandler<T> extends ChannelInboundHandlerAdapter {

	private static final Logger LOGGER = LogManager.getLogger(RpcChannelHandler.class);

	private MessageReceiver<T> receiver;

	public RpcChannelHandler(MessageReceiver<T> receiver) {
		this.receiver = receiver;
	}
	// Netty 5实现
	// @SuppressWarnings("unchecked")
	// @Override
	// public void channelRead(final ChannelHandlerContext ctx, final Object
	// msg) {
	// AttributeKey<Session> sessionKey =
	// AttributeKey.valueOf(RpcConstant.SESSION_KEY);
	// receiver.receive(ctx.attr(sessionKey).get(), (T) msg);
	// }

	// Netty4实现
	@SuppressWarnings("unchecked")
	@Override
	public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
		AttributeKey<Session> sessionKey = AttributeKey.valueOf(RpcConstant.SESSION_KEY);
		receiver.receive(ctx.channel().attr(sessionKey).get(), (T) msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		LOGGER.catching(cause);
		ctx.close();
	}
}